package web.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
import org.springframework.boot.actuate.endpoint.web.WebEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.BasicAuth;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Configuration
public class SwaggerConfig {

    @Getter
    @Setter
    @Value("${springfox.documentation.enabled}")
    private Boolean enable = true;

    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现，
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
//                .pathProvider(new DefaultPathProvider() {
//                    @Override
//                    public String getOperationPath(String operationPath) {
//                        if (contextPath.equals("/"))
//                            return super.getOperationPath(operationPath);
//
//                        if (operationPath.equals("/"))
//                            return super.getOperationPath(operationPath);
//
//                        String path = operationPath.substring(contextPath.length());
//                        return super.getOperationPath(path);
//                    }
//                })
                .select()
                .apis(RequestHandlerSelectors.basePackage("web.controller"))
                .paths(PathSelectors.any())
                .paths(PathSelectors.regex("/error.*").negate())
                .paths(PathSelectors.regex("/actuator.*").negate())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .enable(getEnable());
    }

    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> securitySchemes = new ArrayList<>();
        securitySchemes.add(new BasicAuth("BasicAuth"));
        securitySchemes.add(new ApiKey("Authorization", "Authorization", "header"));
        return securitySchemes;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        //.forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 创建API基本信息,信息会展现在文档页面中
     * 访问地址：http://项目地址/swagger-ui.html
     * 访问地址：http://项目地址/swagger-ui/index.html
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("API Docs").description("Token type is Bearer").build();
    }


    /**
     * 增加如下配置可解决Spring Boot  与Swagger 3.0.0 不兼容问题
     **/
    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        WebMvcEndpointHandlerMapping webMvcEndpointHandlerMapping = new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
        return webMvcEndpointHandlerMapping;
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        boolean mapping = webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
        return mapping;
    }


//apis(RequestHandlerSelectors.basePackage("com.example.demohelloworld.swagger3.controller"))，表明扫描该包下面所有的Controller接口类。
//apis(RequestHandlerSelectors.any())表明扫描所有满足条件的Controller接口类。
//aths(Predicate.not(PathSelectors.regex("/error.*")))表明排除某个路径，在RESTFul接口中有时候需要排除"/error.*"等接口，只需要加入上述代码即可，regex()表明符合正则的路径。


//@Api：用在类上，用来描述整个Controller接口信息。
//@ApiOperation：用在方法上，用来描述方法的基本信息，value是对方法作用的简短描述，notes则是该方法的详细描述。
//@ApiImplicitParam：用在方法上，用来描述方法的参数，paramType是指方法参数类型，可选值有path(参数获取方式@PathVariable)、query(参数获取方式@RequestParam)、header(参数获取方式@RequestHeader)、body(参数获取方式@RequestBody)以及form，name表示参数名字，和参数名字对应，value则是参数描述信息。required表示该字段是否必填，defaultValue表示该字段的默认值，注意，这里的required和defaultValue不具备真正的约束性仅为文档显示，真正的还需要在@RequestParam中设置。
//@ApiImplicitParams：如果是多参数，可将多个参数放在@ApiImplicitParams中，格式为@ApiImplicitParams({@ApiImplicitParam(paramType="query",name="username"),@ApiImplicitParam(paramType="path",name="userid")})。
//@ApiResponse：对响应结果的描述，code表示响应码，@message表示描述信息，如果有多个@ApiResponse，可以放在一个@ApiResponses中。
//@ApiResponses：格式为@ApiResponses({@ApiResponse(code = 200,message = "删除成功！"),@ApiResponse(code = 500,message = "删除失败！")})。
//@ApiModel：一般用于响应类上，表示一个返回响应数据的信息(如updateUse方法，请求参数无法使用@ApiImplicitParam注解进行描述的时候)。
//@ApiModelProperty：用在属性上，描述响应类的属性。
//@ApiIgnore：表述不对某个接口生成文档，即忽略这个接口。

//.excludePathPatterns("/swagger**/**")
//.excludePathPatterns("/webjars/**")
//.excludePathPatterns("/v3/**")
//.excludePathPatterns("/doc.html");


}
